package eteam.aps.systemservice.common;

import cn.hutool.json.JSONUtil;
import eteam.aps.common.exceptions.AuthException;
import eteam.aps.common.helper.Helper;
import eteam.aps.common.helper.JwtUtils;
import eteam.aps.systeminterface.model.dto.VerifyTokenDto;
import eteam.aps.systemservice.bll.SystemBll;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.Objects;

/**
 * 拦截器，处理校验token
 */
public class SystemInterceptor implements HandlerInterceptor {
    @Autowired
    private SystemBll systemBll;
    private long start = 0;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        start = System.currentTimeMillis();
        //Object tmpDto = request.getAttribute("tokenInfo");
        String jsonStr = request.getHeader("tokenInfo");
        VerifyTokenDto tokenDto = StringUtils.isEmpty(jsonStr) ? null : JSONUtil.toBean(URLDecoder.decode(jsonStr.toString(), "UTF-8"), VerifyTokenDto.class);
        if (Objects.isNull(tokenDto)) {
            // 获取Token字符串
            String token = request.getHeader("token");
            if (StringUtils.isEmpty(token)) {
                throw new AuthException("Token无效");
            }
            // 校验Token信息
            jsonStr = JwtUtils.verifyTokenRetJson(token);
            tokenDto = JSONUtil.toBean(jsonStr, VerifyTokenDto.class);
            if (Helper.checkObjAllFieldsIsNull(tokenDto)) {
                throw new AuthException("Token无效");
            }
        }
        request.setAttribute("tokenInfo", tokenDto);
        return true;
        /*return HandlerInterceptor.super.preHandle(request, response, handler);*/
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
            modelAndView) throws Exception {
        System.out.println("Interceptor cost=" + (System.currentTimeMillis() - start));
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

